package sjd.ahsj.springbootmybatisplusoracle.controller;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.google.common.collect.Lists;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import sjd.ahsj.springbootmybatisplusoracle.entity.Anime;
import sjd.ahsj.springbootmybatisplusoracle.entity.AnimeSubscription;
import sjd.ahsj.springbootmybatisplusoracle.entity.BaseUser;
import sjd.ahsj.springbootmybatisplusoracle.entity.UserAmountBill;
import sjd.ahsj.springbootmybatisplusoracle.interceptor.BaseContextHandler;
import sjd.ahsj.springbootmybatisplusoracle.interceptor.IgnoreAuth;
import sjd.ahsj.springbootmybatisplusoracle.model.ReturnObject;
import sjd.ahsj.springbootmybatisplusoracle.service.IBaseUserService;
import sjd.ahsj.springbootmybatisplusoracle.service.IUserAmountBillService;
import sun.misc.BASE64Encoder;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 会员 前端控制器
 * </p>
 *
 * @author zhanghaogao
 * @since 2018-09-18
 */
@Api(description = "用户")
@RestController
@RequestMapping("/baseUser")
public class BaseUserController {
    @Autowired
    private IBaseUserService iBaseUserService;
    @Autowired
    private IUserAmountBillService iUserAmountBillService;

    @ApiOperation("获取用户信息")
    @RequestMapping(value = "/getUserInfo", method = RequestMethod.POST)
    public ReturnObject<BaseUser> getUserInfo() {
        return new ReturnObject(0, "", iBaseUserService.selectById(BaseContextHandler.getUserID()));
    }

    @ApiOperation("修改密码")
    @RequestMapping(value = "/changePassword", method = RequestMethod.POST)
    public ReturnObject changePassword(@ApiParam("原密码") @RequestParam String oldPassword,
                                       @ApiParam("新密码") @RequestParam String password) throws
            UnsupportedEncodingException, NoSuchAlgorithmException {

        BaseUser baseUser = iBaseUserService.selectById(BaseContextHandler.getUserID());
        if (baseUser == null) {
            return new ReturnObject(1, "用户不存在");
        }
        if (!baseUser.getPassword().equals(EncoderByMd5(oldPassword))) {
            return new ReturnObject(1, "原密码错误");
        }
        baseUser.setPassword(EncoderByMd5(password));
        iBaseUserService.updateById(baseUser);
        return new ReturnObject(0, "密码修改成功", baseUser.getId());
    }

    @ApiOperation("获取消费列表")
    @RequestMapping(value = "/getUserAmount", method = RequestMethod.POST)
    public ReturnObject getUserAmount(@RequestParam(defaultValue = "10") int limit,
                                      @RequestParam(defaultValue = "1") int page) {
        EntityWrapper<UserAmountBill> ew = new EntityWrapper<>();
        ew.eq("user_id", BaseContextHandler.getUserID());
        ew.orderBy("crt_time", false);
        return new ReturnObject<>(0, "获取成功", iUserAmountBillService.selectPage(new Page<>(page, limit), ew)
                .getRecords());

    }


    @ApiOperation("获取所有会员")
    @RequestMapping(value = "/getAllUserList", method = RequestMethod.POST)
    public ReturnObject<List<BaseUser>> getAllUserList(@ApiParam("充值用户") String userName,
                                                       @ApiParam("开始时间") @DateTimeFormat(pattern = "yyyy-MM-dd") Date startTime,
                                                       @ApiParam("结束时间") @DateTimeFormat(pattern = "yyyy-MM-dd") Date endTime,
                                                       @RequestParam(defaultValue = "10") int limit,
                                                       @RequestParam(defaultValue = "1") int page) {
        EntityWrapper<BaseUser> ew = new EntityWrapper<>();
        if (StringUtils.isNotBlank(userName)) {
            ew.like("login_name", userName);
        }
        if (startTime != null) {
            ew.gt("crt_time", startTime);
        }
        if (startTime != null) {
            ew.lt("crt_time", endTime);
        }
        ew.orderBy("crt_time", false);
        Page<BaseUser> obj = iBaseUserService.selectPage(new Page<>(page, limit), ew);
        return new ReturnObject(0, "获取成功", obj.getTotal(), obj.getRecords());

    }

    @ApiOperation("获取所有会员的充值记录")
    @RequestMapping(value = "/getAllUserAmount", method = RequestMethod.POST)
    public ReturnObject<List<UserAmountBill>> getAllUserAmount(@RequestParam(defaultValue = "10") int limit,
                                                               @RequestParam(defaultValue = "1") int page,
                                                               @ApiParam("充值用户") String userName,
                                                               @ApiParam("开始时间") @DateTimeFormat(pattern = "yyyy-MM" +
                                                                       "-dd") Date startTime,
                                                               @ApiParam("结束时间") @DateTimeFormat(pattern = "yyyy-MM" +
                                                                       "-dd") Date endTime) {
        EntityWrapper<UserAmountBill> ew = new EntityWrapper<>();
        if (StringUtils.isNotBlank(userName)) {
            ew.like("user.login_name", userName);
        }
        if (startTime != null) {
            ew.gt("info.crt_time", startTime);
        }
        if (startTime != null) {
            ew.lt("info.crt_time", endTime);
        }
        ew.orderBy("crt_time", false);
        Page<UserAmountBill> obj = iUserAmountBillService.selectPage(new Page<>(page, limit), ew);
        return new ReturnObject<>(0, "获取成功", obj.getTotal(), obj.getRecords());

    }

    @IgnoreAuth
    @ApiOperation("注册")
    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public ReturnObject register(@ApiParam("密码") @RequestParam(defaultValue = "111111") String password,
                                 @ApiParam("用户名") String username) throws
            UnsupportedEncodingException, NoSuchAlgorithmException {
        if (StringUtils.isBlank(username)) {
            username = System.currentTimeMillis() + "";
        }
        if (iBaseUserService.selectOne(new EntityWrapper<BaseUser>().eq("login_name", username)) != null) {
            return new ReturnObject(1, "用户已存在");
        }
        BaseUser baseUsers = new BaseUser(0, username, EncoderByMd5(password), 0L, null);
        iBaseUserService.insert(baseUsers);
        return new ReturnObject(0, "注册成功", baseUsers.getId());
    }


    @IgnoreAuth
    @ApiOperation("登陆")
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public ReturnObject login(@ApiParam("密码") @RequestParam String password,
                              @ApiParam("用户名") @RequestParam String username) throws UnsupportedEncodingException,
            NoSuchAlgorithmException {
        BaseUser baseUser = iBaseUserService.selectOne(new EntityWrapper<BaseUser>().eq("login_name", username).eq
                ("password", EncoderByMd5(password)));
        if (baseUser == null) {
            baseUser = iBaseUserService.selectOne(new EntityWrapper<BaseUser>().eq("login_name", username).eq
                    ("password", EncoderByMd5(password)));
            if (baseUser == null) {
                return new ReturnObject(1, "用户名、密码错误");
            }

        }
        return new ReturnObject(0, "登陆成功", baseUser.getId());
    }


    public String EncoderByMd5(String str) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        //确定计算方法
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        BASE64Encoder base64en = new BASE64Encoder();
        //加密后的字符串
        String newstr = base64en.encode(md5.digest(str.getBytes("utf-8")));
        return newstr;
    }
}

